package com.youbug.mall.search.service.impl;

import com.youbug.common.to.PmsAttrTo;
import com.youbug.common.to.PmsBrandTo;
import com.youbug.common.to.es.SkuEsModel;
import com.youbug.mall.search.constant.EsConstant;
import com.youbug.mall.search.feign.ISearchProductFeignService;
import com.youbug.mall.search.service.MallSearchService;
import com.youbug.mall.search.vo.SearchParam;
import com.youbug.mall.search.vo.SearchResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Autowired
    private ISearchProductFeignService ISearchProductFeignService;

    @Override
    public SearchResult search(SearchParam param) {

        SearchResult result = null;

        // 准备检索请求
        SearchHits<SkuEsModel> response = getSearchResponse(param);

        // 分析响应数据，封装成我们需要的格式
        result = buildSearchResult(response, param);
        return result;
    }

    private SearchResult buildSearchResult(SearchHits<SkuEsModel> response, SearchParam param) {
        SearchResult result = new SearchResult();
        List<SearchHit<SkuEsModel>> searchHits = response.getSearchHits();
        List<SkuEsModel> models = searchHits.stream().map(e->{
            SkuEsModel model = e.getContent();

            List<String> skuTitle = e.getHighlightField("skuTitle");
            if(!CollectionUtils.isEmpty(skuTitle)){
                model.setSkuTitle(skuTitle.get(0));
            }
            return model;
         }
        ).collect(Collectors.toList());
        result.setProducts(models);
        // 属性信息
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attrAgg = response.getAggregations().get("attr_agg");

        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            Long attrId = bucket.getKeyAsNumber().longValue();
            attrVo.setAttrId(attrId);

            ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attr_name_agg");

            String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attrName);
            ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attr_value_agg");

            List<String> attrValue = attrValueAgg.getBuckets().stream().map(b -> {
                return ((Terms.Bucket) b).getKeyAsString();
            }).collect(Collectors.toList());

            attrVo.setAttrValue(attrValue);

            attrVos.add(attrVo);
        }

        result.setAttrs(attrVos);

        // 品牌信息
        ParsedLongTerms brandAgg = response.getAggregations().get("brand_agg");

        List<? extends Terms.Bucket> brandAggBuckets = brandAgg.getBuckets();
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        for (Terms.Bucket brandAggBucket : brandAggBuckets) {
            SearchResult.BrandVo vo = new SearchResult.BrandVo();
            String keyAsString = brandAggBucket.getKeyAsString();
            vo.setBrandId(Long.parseLong(keyAsString));

            ParsedStringTerms brandNameAgg = brandAggBucket.getAggregations().get("brand_name_agg");
            String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
            vo.setBrandName(brandName);

            ParsedStringTerms brandImgAgg = brandAggBucket.getAggregations().get("brand_img_agg");
            String brandImg = brandImgAgg.getBuckets().get(0).getKeyAsString();
            vo.setBrandImg(brandImg);

            brandVos.add(vo);
        }
        result.setBrands(brandVos);
        // 分类信息
        ParsedLongTerms catalogAgg = response.getAggregations().get("catalog_agg");
        List<? extends Terms.Bucket> buckets = catalogAgg.getBuckets();
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        for (Terms.Bucket b : buckets) {
            SearchResult.CatalogVo vo = new SearchResult.CatalogVo();
            String keyAsString = b.getKeyAsString();
            vo.setCatalogId(Long.parseLong(keyAsString));

            ParsedStringTerms catalogNameAgg = b.getAggregations().get("catalog_name_agg");
            String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
            vo.setCatalogName(catalogName);

            catalogVos.add(vo);
        }

        result.setCatalogs(catalogVos);

        result.setPageNum(param.getPageNum());

        long total = response.getTotalHits();

        result.setTotal(total);

        //5、2分页信息-总页码-计算
        int totalPages = (int)total % EsConstant.PRODUCT_PAGESIZE == 0 ?
                (int)total / EsConstant.PRODUCT_PAGESIZE : ((int)total / EsConstant.PRODUCT_PAGESIZE + 1);
        result.setTotalPages(totalPages);

        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);
        //6、构建面包屑导航
        List<SearchResult.NavVo> navs = null;
        if(!CollectionUtils.isEmpty(param.getAttrs())){
            if (param.getAttrs() != null && param.getAttrs().size() > 0) {
                navs = param.getAttrs().stream().map(attr -> {
                    //1、分析每一个attrs传过来的参数值
                    SearchResult.NavVo navVo = new SearchResult.NavVo();
                    String[] s = attr.split("_");
                    navVo.setNavValue(s[1]);
                    result.getAttrIds().add(Long.parseLong(s[0]));
                    PmsAttrTo attrTo = ISearchProductFeignService.attrInfo(Long.parseLong(s[0]));
                    if (attrTo != null) {
                        navVo.setNavName(attrTo.getAttrName());
                    } else {
                        navVo.setNavName(s[0]);
                    }
                    //2、取消了这个面包屑以后，我们要跳转到哪个地方，将请求的地址url里面的当前置空
                    //拿到所有的查询条件，去掉当前
                    String replace = replaceQueryString(param, attr,"attrs");
                    navVo.setLink("http://search.gulimall.com/list.html?" + replace);

                    return navVo;
                }).collect(Collectors.toList());
                result.setNavs(navs);
            }
            // 品牌，分类
            if(param.getBrandId()!=null && param.getBrandId().size()>0){
                List<SearchResult.NavVo> navts = result.getNavs();
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                navVo.setNavName("品牌");
                List<PmsBrandTo> brandTos = ISearchProductFeignService.getBrandByIds(param.getBrandId());

                StringBuilder buffer = new StringBuilder();
                String replace = "";
                for (PmsBrandTo brandTo : brandTos) {
                    buffer.append(brandTo.getName());
                    replace = replaceQueryString(param, brandTo.getBrandId()+"","brandId");
                }
                navVo.setNavValue(buffer.toString());

                navVo.setLink("http://search.gulimall.com/list.html?" + replace);
                navts.add(navVo);
                navs.addAll(navts);
            }

        }

        return result;
    }

    private SearchHits<SkuEsModel> getSearchResponse(SearchParam param) {

        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        /**
         * 模糊匹配，过滤（按照属性，分类，品牌，价格区间，库存）
         */
        //1. 构建bool-query
        BoolQueryBuilder boolQueryBuilder=new BoolQueryBuilder();

        //1.1 bool-must
        if(!StringUtils.isEmpty(param.getKeyword())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle",param.getKeyword()).analyzer("ik_smart"));
        }
        //1.2 bool-fiter
        //1.2.1 catelogId
        if(null != param.getCatalog3Id()){
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId",param.getCatalog3Id()));
        }

        //1.2.2 brandId
        if(null != param.getBrandId() && param.getBrandId().size() >0){
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId",param.getBrandId()));
        }

        //1.2.3 attrs
        if(param.getAttrs() != null && param.getAttrs().size() > 0){

            param.getAttrs().forEach(item -> {
                //attrs=1_5寸:8寸&2_16G:8G
                BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();


                //attrs=1_5寸:8寸
                String[] s = item.split("_");
                String attrId=s[0];
                String[] attrValues = s[1].split(":");//这个属性检索用的值
                boolQuery.must(QueryBuilders.termQuery("attrs.attrId",attrId));
                boolQuery.must(QueryBuilders.termsQuery("attrs.attrValue",attrValues));

                NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("attrs",boolQuery, ScoreMode.None);
                boolQueryBuilder.filter(nestedQueryBuilder);
            });

        }

        //1.2.4 hasStock
        if(null != param.getHasStock()){
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock",param.getHasStock() == 1));
        }

        //1.2.5 skuPrice
        if(!StringUtils.isEmpty(param.getSkuPrice())){
            //skuPrice形式为：1_500或_500或500_
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("skuPrice");
            String[] price = param.getSkuPrice().split("_");
            if(price.length==2){
                rangeQueryBuilder.gte(price[0]).lte(price[1]);
            }else if(price.length == 1){
                if(param.getSkuPrice().startsWith("_")){
                    rangeQueryBuilder.lte(price[1]);
                }
                if(param.getSkuPrice().endsWith("_")){
                    rangeQueryBuilder.gte(price[0]);
                }
            }
            boolQueryBuilder.filter(rangeQueryBuilder);
        }
        queryBuilder.withQuery(boolQueryBuilder);

        /**
         * 排序，分页，高亮
         */
        //排序
        //形式为sort=hotScore_asc/desc
        if(!StringUtils.isEmpty(param.getSort())){
            String sort = param.getSort();
            String[] sortFileds = sort.split("_");

            SortOrder sortOrder="asc".equalsIgnoreCase(sortFileds[1])?SortOrder.ASC:SortOrder.DESC;

            FieldSortBuilder order = SortBuilders.fieldSort(sortFileds[0]).order(sortOrder);

            queryBuilder.withSort(order);
        }
        //分页
        queryBuilder.withPageable(PageRequest.of((param.getPageNum()-1)* EsConstant.PRODUCT_PAGESIZE, EsConstant.PRODUCT_PAGESIZE));

        //高亮
        if(!StringUtils.isEmpty(param.getKeyword())){

            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");

            queryBuilder.withHighlightBuilder(highlightBuilder);
        }

        /**
         * 聚合分析
         */
        //1. 按照品牌进行聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg")
                .field("brandId").size(50);

        //1.1 品牌的子聚合-品牌名聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg")
                .field("brandName").size(1));
        //1.2 品牌的子聚合-品牌图片聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg")
                .field("brandImg").size(1));

        queryBuilder.addAggregation(brand_agg);

        //2. 按照分类信息进行聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg");
        catalog_agg.field("catalogId").size(20);

        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));

        queryBuilder.addAggregation(catalog_agg);

        //2. 按照属性信息进行聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        //2.1 按照属性ID进行聚合
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        attr_agg.subAggregation(attr_id_agg);
        //2.1.1 在每个属性ID下，按照属性名进行聚合
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        //2.1.1 在每个属性ID下，按照属性值进行聚合
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        queryBuilder.addAggregation(attr_agg);

        NativeSearchQuery query = queryBuilder.build();

        SearchHits<SkuEsModel> search = elasticsearchRestTemplate.search(query, SkuEsModel.class, IndexCoordinates.of(EsConstant.PRODUCT_INDEX));

        return search;
    }

    private String replaceQueryString(SearchParam param, String value, String key) {
        String encode = null;
        try {
            encode = URLEncoder.encode(value, "UTF-8");
            encode = encode.replace("+", "%20");  //浏览器对空格的编码和Java不一样，差异化处理
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return param.get_queryString().replace("&"+key+"=" + encode, "");
    }

}